<?php
namespace Admin\Controller;
use Lib\Controller;
class LoginController extends Controller {

	private $manager_model;
	
	public function _initialize(){
		$this->manager_model = getInstance('Admin\Model\ManagerModel');
	}

	/**
	 * 登陆界面及验证
	 */
    public function login() {
		if(count($_POST) > 0){
    		$username = $_POST['username'];
    		$password = $_POST['password'];
    		$verify = $_POST['verify'];
    		if(empty($username)){
    			$this->returnJson(201);
    		}else if(empty($password)){
    			$this->returnJson(202);
     		}else if(empty($verify)){
    			$this->returnJson(206);
			}else if($_SESSION['VerifyCode'] != $verify){
    			$this->returnJson(207);
    		}else{
    			$password = md5($password);
    			if($manager_info = $this->manager_model->field('uid,username,role_id,state')->where("username='$username' AND password='$password'")->find()){
    				if($manager_info['state'] == 'D'){
    					$this->returnJson(203);
    				}else{
						unset($_SESSION['VerifyCode']);
    					$role_info = getInstance('Admin\Model\RoleModel')->field('name')->where("id={$manager_info['role_id']}")->find();
    					$manager_info['role_name'] = $role_info['name'];
    					$_SESSION['SESSION_USER'] = (array)$manager_info;
    					$this->manager_model->where("uid={$manager_info['uid']}")->update(array('login_ip'=>get_client_ip(), 'login_time'=>date('Y-m-d H:i:s')));
    					$this->returnJson(200, $manager_info);
    				}
    			}else{
    				$this->returnJson(204);
				}
    		}
		}else{
			$this->display('Admin/View/Login/login.php');
		}
	}	
	
	/**
	 * 用户退出
	 */
	public function logout() {
		unset ($_SESSION['SESSION_USER']);
		session_destroy();
		R('login.php');
	}	
	
	/**
	 * 弹出登录框
	 */
	public function loginDialogAction(){
		$this->display();
	}

	/**
	 * 获取验证码
	 */
	public function getVerifyCode(){
		import('Util.Verify.Verify');
		new \Verify(4,15);
	}

	/**
     * 按照某种格式返回数据
     */
    public function returnJson($code, $list=''){
		$message = array(
			200 => '操作成功',
			201 => '用户名为空',
			202 => '用户密码为空',
			203 => '用户已被锁定',
			204 => '用户名或密码错误',
			205 => '用户会话key不存在',
			206 => '验证码为空',
			207 => '验证码错误',
			208 => '参数有误'
		);
    	$data = array('statusCode'=>$code, 'message'=>$message[$code], 'sessionId'=>session_id());
    	if(!empty($list)){
    		$data['data'] = $list;
    	}
    	exit(json_encode($data));
    }
    

}
?>